package com.brother.rest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class RestSessionManager {
	private static List<RestSessionData> session = new CopyOnWriteArrayList<RestSessionData>(); 
	
	private static RestSessionManager instance = new RestSessionManager();
	
	private RestSessionManager(){}
	
	public static RestSessionManager getInstance(){
		return instance;
	}
	
	public void setAttribute(String key, Object o){
		RestSessionData s = new RestSessionData();
		s.key = key;
		s.time = System.currentTimeMillis();
		s.object = o;
		session.add(s);
		removeExpire();
	}
	
	public Object getAttribute(String key){
		removeExpire();
		for(RestSessionData s : session){
			if(s.key.equals(key)){
				return s.object;
			}
		}
		return null;
	}
	
	public void removeExpire(){
		List<RestSessionData> removes = new ArrayList<RestSessionData>();
		long now = System.currentTimeMillis();
		for(RestSessionData s : session){
			if(now - s.time > RestSessionData.expiresMil){
				removes.add(s);
			}
		}
		session.removeAll(removes);
	}
	
}
